package com.csdj.newsmanger.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    @GetMapping("/up")
    public String upload(){

        return "upload";
    }

    @PostMapping("/uploads")
    @ResponseBody
    public Map<String,Object> upload(HttpServletRequest request){
      //  multipartFile.tr
        Map<String,Object> map=new HashMap<>();
        MultipartHttpServletRequest mr= (MultipartHttpServletRequest) request;
        MultipartFile mf= mr.getFile("filename");
        //获取上下文的 文件上传地址
        //String path=request.getSession().getServletContext().getRealPath("upload");

       // System.out.println(resource.getFile().getAbsolutePath());
        String path = null;
        try {
            path = ResourceUtils.getURL("classpath:").getPath();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println(path);

        //设置编译后文件存在路径
       // String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/images/tx/";
        //获取项目路径
        File directory = new File("src/main/resources/static/upload");
        try {

             path = directory.getCanonicalPath();
        } catch (IOException e) {
            e.printStackTrace();
        }

        File files=new File(path);
        if(!files.exists()){
            files.mkdir();
        }
        //判断内容不为空
        if(mf!=null&&!mf.isEmpty()){
            String fileName=mf.getOriginalFilename();
            System.out.println(fileName);
            try {
                //transferTo(地址,文件) 把文件上传到指定的
                mf.transferTo(new File(path,fileName));
               map.put("code",200);
               map.put("msg","文件上传成功!");
            } catch (IOException e) {
                map.put("code",300);
                map.put("msg","文件上传失败!");
                 e.printStackTrace();

            }
        }

        return map;
    }

}
